package com.song.cmsservice.controller.msmcontroller;

import com.song.cmsservice.service.MsmService;
import com.song.cmsservice.utils.RandomUtil;
import com.song.commonutils.ResultObj;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author song
 * @data 2020/4/4
 */
@RequestMapping("/edumsm/msm")
@RestController
@Api(description = "短信发送")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    /**
     * 发送短信
     * @param phone
     * @return
     */
    @ApiOperation(value = "发送短信")
    @GetMapping("/send/{phone}")
    public ResultObj sendMsm(@PathVariable String phone){
        String code = redisTemplate.opsForValue().get(phone);
        if(code!=null){
            return ResultObj.ok();
        }
        //生成随机值
        code= RandomUtil.getFourBitRandom();
        Map<String,Object> map=new HashMap<>();
        map.put("code",code);
        boolean isSend=msmService.send(map,phone);
        if(isSend){
            //发送成功存redis 设置有效时间5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return ResultObj.ok().message("短息发送成功");
        }else {
            return ResultObj.error().message("短息发送失败");
        }
    }
}
